package pers.qianyu.month_202011.date_20201117;

/**
 * 337. 打家劫舍 III
 * https://leetcode-cn.com/problems/house-robber-iii/
 *
 * @author mizzle rain
 * @date 2020-11-17 22:25
 */
public class RobThree2 {
    public int rob(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] result = recur(root);
        return Math.max(result[0], result[1]);
    }

    /**
     * 优化版动态规划
     */
    private int[] recur(TreeNode node) {
        if (node == null) {
            return new int[]{0, 0};
        }
        int[] left = recur(node.left);
        int[] right = recur(node.right);
        int selected = node.val + left[1] + right[1];
        int noSelected = Math.max(left[0], left[1]) +
                Math.max(right[1], right[0]);
        return new int[]{selected, noSelected};
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}



